package com.test.util;

import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;

/**
 *
 */
public class Base64Util {

    private static final String CHARSET = "UTF-8";

    /**
     * 解密
     *
     * @param data
     * @return
     */
    public static byte[] decode(String data) {
        try {
            if (null == data) {
                return null;
            }
            return Base64.decodeBase64(data.getBytes(CHARSET));
        } catch (UnsupportedEncodingException e) {
            System.out.println(String.format("字符串：%s，解密异常", data) + e);
            return null;
        }
    }

    /**
     * 加密
     *
     * @param data
     * @return
     */
    public static String encode(byte[] data) {
        try {
            if (null == data) {
                return null;
            }
            return new String(Base64.encodeBase64(data), CHARSET);
        } catch (UnsupportedEncodingException e) {
            System.out.println(String.format("字符串：%s，加密异常", data) + e);
            return null;
        }
    }


    public static void main(String[] args) {
        //加密
        String encode = encode("alskdjfa".getBytes());
        //解密
        byte[] decode = decode(encode);
        if (decode != null) {
            System.out.println(new String(decode));
        }

    }
}

